//
//  BN_TakePhotoController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-19.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_TakePhotoController.h"

@interface BN_TakePhotoController ()
@end

@implementation BN_TakePhotoController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets {}


- (void)didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL error:(NSError *)error {

}

- (void)captureManager:(AVCaptureManager *)captureManager didFailWithError:(NSError *)error {

}

- (void)captureManagerStillImageCaptured:(AVCaptureManager *)captureManager {

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.takePhotoBtn addTarget:self action:@selector(takePhotoAction) forControlEvents:UIControlEventTouchUpInside];
    // captureManager
    self.captureManager = [[AVCaptureManager alloc] initWithPreviewView:self.view];
    self.captureManager.delegate = self;
    
    // close
    [self.backVcBtn addTarget:self action:@selector(backVCtrlAction:) forControlEvents:UIControlEventTouchUpInside];
    self.backVcBtn.highlightedGlowColor = [UIColor whiteColor];
    self.backVcBtn.glowsWhenHighlighted = YES;
    
    // 拿到最后一张IMG，从相册
    /*__block BN_TakePhotoController *blockSelf_ = self;
    NSString *XHCameraModePhoto = ALAssetTypePhoto;
    [self updateLibraryButtonWithCameraMode:XHCameraModePhoto didFinishcompledBlock:^(UIImage *thumbnail) {
        blockSelf_.lastPhotoImageView.image = thumbnail;
    }];
    
    self.lastPhotoImageView.layer.masksToBounds = YES;
    self.lastPhotoImageView.layer.cornerRadius = 6.0;
    self.lastPhotoImageView.layer.borderWidth = 0.1;
    self.lastPhotoImageView.layer.borderColor = [[UIColor whiteColor] CGColor];*/
    
    // UI
    NSInteger viewHieght = FULLSCREEN_HEIGHT;
    if (viewHieght <=480) {
        self.bottomView.frame = CGRectMake(0, FULLSCREEN_HEIGHT-119, SCREEN_WIDTH, 119);
        self.lastPhotoImageView.frame = CGRectMake(14, (119-43)/2, 43, 43);
        self.takePhotoBtn.frame = CGRectMake((SCREEN_WIDTH-73)/2, (119-73)/2, 73, 73);
    }

    self.lastPhotoImageView.hidden = YES;
}

// 从相册中抽出最后一张图片
- (void)updateLibraryButtonWithCameraMode:(NSString *)cameraMode didFinishcompledBlock:(void (^)(UIImage *thumbnail))compled {
    __block NSString *assetPropertyType = nil;
    __block NSMutableArray *assets = [[NSMutableArray alloc] init];
    //    if (cameraMode == XHCameraModePhoto) {
    //        assetPropertyType = [ALAssetTypePhoto copy];
    //    } else if (cameraMode == XHCameraModeVideo) {
    //        assetPropertyType = [ALAssetTypeVideo copy];
    //    }
    assetPropertyType = cameraMode;
    
    void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
    {
        if (group == nil)
        {
            return;
        }
        *stop = YES;
        
        __block int num = 0;
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
         {
             if(result == nil)
             {
                 return;
             }
             __block ALAsset *assetResult = result;
             num++;
             NSInteger numberOf = [group numberOfAssets];
             
             NSString *al_assetPropertyType = [assetResult valueForProperty:ALAssetPropertyType];
             if ([al_assetPropertyType isEqualToString:assetPropertyType]) {
                 [assets addObject:assetResult];
             }
             
             if (num == numberOf) {
                 UIImage *img = [UIImage imageWithCGImage:[[assets lastObject] thumbnail]];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     if (compled) {
                         compled(img);
                     }
                 });
             }
         }];
    };
    
    // Group Enumerator Failure Block
    void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *img = [UIImage imageNamed:@"photo_Library.png"];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (compled) {
                    compled(img);
                }
            });
        });
    };
    // Enumerate Albums
    ALAssetsLibrary *library_ = [[ALAssetsLibrary alloc] init];
    [library_ enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
                            usingBlock:assetGroupEnumerator
                          failureBlock:assetGroupEnumberatorFailure];
}

- (void)backVCtrlAction:(UITapGestureRecognizer *)tap {
    
    [self realseResource];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)takePhotoAction {
    [[self captureManager] captureStillImage];
}

- (void)backImgInfo:(UIImage *)image {
    UIImage *newImage = image;
    newImage = [newImage rotateImageByAngle:@"90"];
    newImage = [self cutCenterImage:newImage size:CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH)];
    self.backImgInfo(newImage);
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)getTodealWith:(BackIMGInfo)backIMGinfo {
    self.backImgInfo = backIMGinfo;
}

#pragma mark
#pragma mark 工具

// 根据size截取图片中间矩形区域的图片 这里的size是正方形
- (UIImage *)cutCenterImage:(UIImage *)image size:(CGSize)size{
    CGSize imageSize = image.size;
    CGRect rect;
    //根据图片的大小计算出图片中间矩形区域的位置与大小
    if (imageSize.width > imageSize.height) {
        float leftMargin = (imageSize.width - imageSize.height) * 0.5;
        rect = CGRectMake(leftMargin, 0, imageSize.height, imageSize.height);
    }else{
        float topMargin = (imageSize.height - imageSize.width) * 0.5;
        rect = CGRectMake(0, topMargin, imageSize.width, imageSize.width);
    }
    
    CGImageRef imageRef = image.CGImage;
    //截取中间区域矩形图片
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
    
    UIImage *tmp = [[UIImage alloc] initWithCGImage:imageRefRect];
    CGImageRelease(imageRefRect);
    
    UIGraphicsBeginImageContext(size);
    CGRect rectDraw = CGRectMake(0, 0, size.width, size.height);
    [tmp drawInRect:rectDraw];
    // 从当前context中创建一个改变大小后的图片
    tmp = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return tmp;
}

#pragma mark
#pragma mark 生命周期

- (void)realseResource {
    
}

- (void)dealloc {
    NSLog(@"个人设置拍照界面释放...");
}
@end
